package com.tjbank.cssys.web.config;

import com.tjbank.cssys.domain.CkErrorLog;
import com.tjbank.cssys.web.service.CkErrorLogService;
import com.tjbank.cssys.web.util.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

@RestControllerAdvice
public class ControllerExceptionHandleAdive {
    private static Logger log=LoggerFactory.getLogger(ControllerExceptionHandleAdive.class);
   @Autowired
   private CkErrorLogService ckErrorLogService;
    @ExceptionHandler
    public CommonResult handler(HttpServletRequest request, HttpServletResponse response,Exception e){
        log.error("---CE:"+request.getRemoteHost()+":"+request.getServerPort()+request.getRequestURI()+":请求异常......");
        int param=(int)(Math.random()*900)+100;
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date(System.currentTimeMillis());
        CkErrorLog ckErrorLog=new CkErrorLog();
        ckErrorLog.setErrorUrl(request.getRequestURI());
        ckErrorLog.setTimeStamp(simpleDateFormat.format(date));
        if(response.getStatus()== HttpStatus.BAD_REQUEST.value()){
            log.error("修改返回状态值为200");
            response.setStatus(HttpStatus.OK.value());
        }
        if(e instanceof NullPointerException){
            ckErrorLog.setErrorCode("2011BCE000"+param);
            ckErrorLog.setErrorMess(e.getMessage());
            log.error("code:00:"+e.getMessage(),e);
            ckErrorLogService.insertCkErrotLog(ckErrorLog);
            return CommonResult.failed("发生空指针异常");
        }else if(e instanceof IllegalArgumentException){
            ckErrorLog.setErrorCode("2011BCE000"+param);
            ckErrorLog.setErrorMess(e.getMessage());
            log.error("code:01 "+e.getMessage(),e);
            ckErrorLogService.insertCkErrotLog(ckErrorLog);
            return  CommonResult.failed("请求参数不匹配");
        }else if(e instanceof SQLException){
            ckErrorLog.setErrorCode("2011BCE000"+param);
            ckErrorLog.setErrorMess(e.getMessage());
            log.error("code:02 "+e.getMessage(),e);
            ckErrorLogService.insertCkErrotLog(ckErrorLog);
            return  CommonResult.failed("数据库访问异常：");
        }else{
            ckErrorLog.setErrorCode("2011BCE000"+param);
            ckErrorLog.setErrorMess(e.getMessage());
            log.error("code:99 "+e.getMessage(),e);
            ckErrorLogService.insertCkErrotLog(ckErrorLog);
            return  CommonResult.failed("服务器异常，请联系管理员");
        }
    }
}
